package main

import (
	"fmt"
	"github.com/spf13/viper"
	"os"
)

/**
statetransfer:
    recoverdamage: true
    blocksperrequest: 20
    maxdeltas: 200
    timeout:
        singleblock: 2s
        singlestatedelta: 2s
        fullstate: 60s
peer:
    abcd:   3322d
hosts:
- localhost
- 172.29.49.141
- 172.29.49.144
- 127.0.0.1
*/
type Config struct {
	Statetransfer statetransfer `mapstructure:statetransfer`
	Peer          peer          `mapstructure:peer`
	Hosts         []string      `mapstructure:hosts`
}
type statetransfer struct {
	Recoverdamage    bool
	Blocksperrequest uint
	Maxdeltas        uint
	Timeout          timeout `mapstructure:timeout`
}
type peer struct {
	Abcd string
}
type timeout struct {
	Singleblock      string
	Singlestatedelta string
	Fullstate        string
}

func main() {
	dir, _ := os.Getwd()

	//a。如果配置无后缀，需指定type
	viper.SetConfigName("config_no_extant")
	viper.SetConfigType("yaml")
	//b。如果配置有后缀，无需指定type
	//viper.SetConfigName("config_struct")

	viper.AddConfigPath(dir)
	viper.AddConfigPath(".")
	viper.AddConfigPath("viper_struct")
	if err_ := viper.ReadInConfig(); err_ != nil {
		//排查错误： 找不到配置文件
		panic(err_)
	}
	c := Config{} //实例化
	if err := viper.Unmarshal(&c); err != nil {
		//排查错误： 反序列化到结构体时可能类型出错
		panic(fmt.Sprintf("反序列化发生错误：%s", err))
	}
	if c.Hosts == nil {
		panic("获取到hosts配置为空，无法继续")
	}
	fmt.Println(c.Hosts[1])
	fmt.Println(c.Statetransfer.Timeout.Fullstate)
}
